package com.angus.common.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
import com.angus.common.core.annotation.Device;
import com.angus.common.core.constant.DeviceConstants;

/**
 * @author YourName
 * @date 20250622
 * @description 设备信息验证器，用于验证手机和邮箱信息
 */
public class DeviceValidator implements ConstraintValidator<Device, DeviceConstants> {

    // 手机号正则
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    // 邮箱正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$");

    @Override
    public boolean isValid(DeviceConstants entity, ConstraintValidatorContext context) {
        if (entity == null) {
            return true;
        }

        // 直接访问成员变量
        Integer type = entity.type;
        String device = entity.device;

        // 空值校验（根据需求调整）
        if (device == null || device.trim().isEmpty()) {
            return false;
        }

        // 根据 type 选择验证逻辑
        if (type != null) {
            if (type == 1) {
                // 手机验证
                return PHONE_PATTERN.matcher(device).matches();
            } else if (type == 2) {
                // 邮箱验证
                return EMAIL_PATTERN.matcher(device).matches();
            }
        }

        // 未知类型
        return false;
    }
}